package com.dbflow5.adapter.queriable;

import com.dbflow5.adapter.CacheAdapter;
import com.dbflow5.database.DatabaseWrapper;
import com.dbflow5.database.FlowCursor;
import com.dbflow5.query.cache.ModelCache;

/**
 * Description: More optimized version of [CacheableModelLoader] which assumes that the [Model]
 * only utilizes a single primary key.
 */
public class SingleKeyCacheableModelLoader<T> extends CacheableModelLoader<T>{

    public SingleKeyCacheableModelLoader(Class<T> modelClass, CacheAdapter<T> cacheAdapter){
        super(modelClass, cacheAdapter);
    }

    /**
     * Converts data by loading from cache based on its sequence of caching ids. Will reuse the passed
     * [T] if it's not found in the cache and non-null.
     *
     * @param cursor cursor
     * @param moveToFirst moveToFirst
     * @param databaseWrapper databaseWrapper
     * @return A model from cache.
     */
    @Override
    public T convertToData(FlowCursor cursor, boolean moveToFirst, DatabaseWrapper databaseWrapper) {
        if (!moveToFirst || cursor.goToFirstRow()) {
            Object value = cacheAdapter.getCachingColumnValueFromCursor(cursor);
            return ModelCache.addOrReload(modelCache, value, cacheAdapter, modelAdapter, cursor, databaseWrapper);
        }
        return null;
    }
}
